package com.meilai.project.service.administration.goods.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.administration.goods.GoodsOutStorageDTO;
import com.meilai.project.dto.administration.goods.GoodsOutStorageSearchDTO;
import com.meilai.project.entity.administration.goods.GoodsOutStorage;
import com.meilai.project.entity.administration.goods.GoodsStorageChangeRecord;
import com.meilai.project.entity.administration.goods.GoodsStorageManage;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.administration.goods.GoodsOutStorageMapper;
import com.meilai.project.service.administration.goods.GoodsOutStorageService;
import com.meilai.project.service.administration.goods.GoodsStorageChangeRecordService;
import com.meilai.project.service.administration.goods.GoodsStorageManageService;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.vo.administration.goods.GoodsOutStorageVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Log4j2
public class GoodsOutStorageServiceImpl extends ServiceImpl<GoodsOutStorageMapper, GoodsOutStorage> implements GoodsOutStorageService {

    @Autowired
    private GoodsStorageManageService goodsStorageManageService;


    @Autowired
    private GoodsStorageChangeRecordService goodsStorageChangeRecordService;

    @Override
    public Page<GoodsOutStorageVO> selectPageList(Integer current_page, Integer page_size, GoodsOutStorageSearchDTO searchDTO) {
        Page<GoodsOutStorageVO> page = new Page<>(current_page, page_size);
        List<GoodsOutStorageVO> list = baseMapper.selectPageList(page, searchDTO);
        return page.setRecords(list);
    }


    @Override
    public GoodsOutStorageVO getOneById(Long id) {
        GoodsOutStorageVO goodsOutStorageVO = baseMapper.selectOneById(id);
        if (goodsOutStorageVO == null) {
            throw new CommonException("数据不存在");
        }
        return goodsOutStorageVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(GoodsOutStorageDTO dto) {
        Long user_id = ThreadLocalUserUtil.get().getId();
        // 添加出库记录
        GoodsOutStorage goodsOutStorage = new GoodsOutStorage();
        BeanUtils.copyProperties(dto, goodsOutStorage);
        goodsOutStorage.setUser_id(user_id);
        this.save(goodsOutStorage);
        // 查询库存
        GoodsStorageManage one = goodsStorageManageService.getOne(Wrappers.<GoodsStorageManage>lambdaQuery().eq(GoodsStorageManage::getGoods_type_id, dto.getGoods_type_id()));
        if (one == null) {
            throw new CommonException("物品不存在");
        } else {
            if (one.getStorage_number() < dto.getNumber()) {
                throw new CommonException("出库的数量不能大于库存数量");
            } else {
                // 添加库存改变记录
                GoodsStorageChangeRecord record = new GoodsStorageChangeRecord();
                record.setType(2);
                record.setChange_time(LocalDateTime.now());
                record.setOperator_id(user_id);
                record.setBefore_change_number(one.getStorage_number());
                record.setAfter_change_number(one.getStorage_number() - dto.getNumber());
                record.setChange_number(dto.getNumber());
                record.setGoods_type_id(dto.getGoods_type_id());
                record.setData_id(goodsOutStorage.getId());
                goodsStorageChangeRecordService.save(record);
                one.setStorage_number(one.getStorage_number() - dto.getNumber());
                goodsStorageManageService.updateById(one);
            }
        }
        return true;
    }

//    @Override
//    @Transactional
//    public boolean begin(GoodsOutStorageDTO dto) {
//        // 提交
//        int flowResult = saveAndBegin(dto, false);
//        Long number = dto.getNumber();
//        GoodsStorageManageDTO goodsStorageManageDTO = new GoodsStorageManageDTO();
//        goodsStorageManageDTO.setSupplier_id(dto.getSupplier_id());
//        goodsStorageManageDTO.setSupplier_goods_id(dto.getSupplier_goods_id());
//        if (flowResult == 1) {
//            // 仍在流程中
//            // 更新库存表
//            goodsStorageManageDTO.setLock_number(number);
//            boolean flag = goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//            return flag;
//        } else if (flowResult == 2) {
//            // 无审批节点，直接结束
//            // 更新库存表
//            goodsStorageManageDTO.setOut_number(number);
//            boolean flag = goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//            return flag;
//        } else {
//            throw new CommonException("提交失败，请联系管理员！");
//        }
//        return false;
//    }

//    @Override
//    @Transactional
//    public boolean pass(GoodsOutStorageCheckDTO dto) {
//        // 通过
//        int flowResult = passAndBack(dto, true, false);
//        if (flowResult == 1) {
//            // 通过后仍然在流程中
//            return true;
//        } else if (flowResult == 2) {
//            // 审核后流程结束
//            // 更新库存表
//            GoodsOutStorage temp = getOneById(dto.getId());
//            Long number = temp.getNumber();
//            GoodsStorageManageDTO goodsStorageManageDTO = new GoodsStorageManageDTO();
//            goodsStorageManageDTO.setSupplier_id(temp.getSupplier_id());
//            goodsStorageManageDTO.setSupplier_goods_id(temp.getSupplier_goods_id());
//            goodsStorageManageDTO.setOut_number(number);
//            goodsStorageManageDTO.setLock_number(-number);
//            boolean flag = goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//
//            return flag;
//        } else {
//            throw new CommonException("通过失败，请联系管理员！");
//        }
//        return false;
//    }
//
//    @Override
//    @Transactional
//    public boolean returnBack(GoodsOutStorageCheckDTO dto) {
//        // 驳回
//        int flowResult = passAndBack(dto, false, false);
//        if (flowResult == 1) {
//            //驳回到初始成功，需要清除锁定库存
//            // 更新库存表
//            GoodsOutStorage temp = getOneById(dto.getId());
//            Long number = temp.getNumber();
//            GoodsStorageManageDTO goodsStorageManageDTO = new GoodsStorageManageDTO();
//            goodsStorageManageDTO.setSupplier_id(temp.getSupplier_id());
//            goodsStorageManageDTO.setSupplier_goods_id(temp.getSupplier_goods_id());
//            goodsStorageManageDTO.setLock_number(-number);
//            boolean flag = goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//
//            return flag;
//        } else {
//            throw new CommonException("驳回失败，请联系管理员！");
//        }
//        return false;
//    }

//    @Override
//    @Transactional
//    public boolean actualDelete(Long id) {
//        int flowResult = deleteAndActualDel(id, true);
//        if (flowResult != 1) throw new CommonException("彻底删除失败，请联系管理员！");
//        return true;
//    }
//
//
//    @Override
//    @Transactional
//    public boolean delete(Long id) {
//        int flowResult = deleteAndActualDel(id, false);
//        if (flowResult != 1) throw new CommonException("删除失败，请联系管理员！");
//        return true;
//    }
//
//
//    @Override
//    public List<GoodsOutStorageVO> selectOwnList() {
//        // 当前人id
//        Long userId = ThreadLocalUserUtil.get().getId();
//        return baseMapper.selectOwnList(userId);
//    }
//
//    // 保存 和 提交 抽出相同代码
//    private int saveAndBegin(GoodsOutStorageDTO dto, boolean isSave) {
//        // 获取当前人的id和部门id
//        UserForWFVO user = UserServiceImpl.getUserForWF(dto);
//        // 业务数据
//        GoodsOutStorage temp = new GoodsOutStorage();
//        BeanUtils.copyProperties(dto, temp);
//
//        // 当前人
//        UserVO user_1 = ThreadLocalUserUtil.get();
//        // 设置流程字段，flow_type请自行对应“dict_flow_type”表中的id， 比如当前入职流程（考察登记流程）的id是5
//        String flow_title = user_1.getName() + "的出库申请"; // 审批流程的名称，需要根据实际业务自行确定
//        FlowBusinessDataSuperEntity fbdse = WorkFlowUtil.getStartSuperDataEntity(
//                user.getUser_id(),  // 当前用户id
//                user.getDep_id(), // 提交的部门id
//                13, // 流程类型id，“dict_flow_type”表中的id
//                flow_title // 自定义的流程标题
//        );
//        BeanUtils.copyProperties(fbdse, temp);
//        // 是否为新数据
//        // 新数据时，前端不传业务数据id
//        // 非新数据时，即来源是“草稿箱”、“已删除”、“被退回”时，前端需要传入业务数据id
//        boolean isFirst = (dto.getId() == null);
//
//        // 由于流程字段含有id，会覆盖数据，此处需要手动setId
//        if (!isFirst) temp.setId(dto.getId());
//
//        // 新增或更新业务数据
//        boolean flag;
//        if (isFirst) {
//            flag = save(temp);
//        } else {
//            //提交需校验库存量是否足够，不足无法提交
//            boolean flag_1 = goodsStorageManageService.checkGoodsStorage(temp.getNumber(), temp.getSupplier_id(), temp.getSupplier_goods_id());
//            if (flag_1) {
//                flag = updateById(temp);
//            } else {
//                flag = false;
//            }
//
//        }
//        if (!flag) throw new CommonException("保存失败");
//
//        // 构造流程工具类
//        WorkFlowUtil wfu = new WorkFlowUtil<GoodsOutStorage, GoodsOutStorageMapper>(temp.getId(), user.getUser_id(), GoodsOutStorage.class);
//
//        // 审批流程id
//        // 新数据,传0L
//        // 非新数据,根据数据id,查找wfData_id
//        Long wfData_id = isFirst ? 0L : wfu.getWfDataId(dto.getId());
//        // 旧数据记录留存
//        GoodsOutStorage old_data = isFirst ? new GoodsOutStorage() : temp;
//
//        return isSave ? wfu.SaveDraft(wfData_id) : wfu.Begin(wfData_id, "", old_data);
//    }
//
//    // 通过 和 驳回 抽出相同代码
//    private int passAndBack(GoodsOutStorageCheckDTO dto, boolean isPass, boolean... updateData) {
//        // 当前人id
//        Long userId = ThreadLocalUserUtil.get().getId();
//        // 若业务数据有审批中可修改的内容，请自行更新
//        if (updateData != null && updateData[0]) {
//            GoodsOutStorage updateTemp = new GoodsOutStorage();
//            BeanUtils.copyProperties(dto, updateTemp);
//            updateById(updateTemp);
//        }
//
//        // 业务数据
//        GoodsOutStorage temp = getById(dto.getId());
//
//        // 构造流程工具类
//        WorkFlowUtil wfu = new WorkFlowUtil<GoodsOutStorage, GoodsOutStorageMapper>(dto.getId(), userId, GoodsOutStorage.class);
//
//        // 审批入参类
//        WorkFlowCheckDTO checkDTO = WorkFlowCheckDTO.getWorkFlowCheckDTO(
//                temp.getFlow_current_node_id(), // 当前节点id
//                temp.getFlow_json(), // 流程json
//                dto.getWf_check_opinion(), // 审批意见
//                dto.getWf_check_sign_url(), // 审批签名链接
//                JSONObject.toJSONString(temp) // 旧数据留存
//        );
//
//        // 审批
//        return isPass ? wfu.ToNext(checkDTO) : wfu.ReturnBack(checkDTO);
//    }
//
//    // 删除 和 彻底删除 抽出相同代码
//    private int deleteAndActualDel(Long id, boolean isActual) {
//        // 当前人id
//        Long userId = ThreadLocalUserUtil.get().getId();
//        //业务数据，删除出库表同时处理库存表库存
//        GoodsOutStorage goodsOutStorage = getById(id);
//        Integer flow_status = goodsOutStorage.getFlow_status();
//        Long number = goodsOutStorage.getNumber();
//        GoodsStorageManageDTO goodsStorageManageDTO = new GoodsStorageManageDTO();
//        goodsStorageManageDTO.setSupplier_id(goodsOutStorage.getSupplier_id());
//        goodsStorageManageDTO.setSupplier_goods_id(goodsOutStorage.getSupplier_goods_id());
//        boolean flag = false;
//        if (flow_status != null && flow_status == 3) {
//            // 删除进行中的出库单，需更新库存表-锁定量
//            goodsStorageManageDTO.setLock_number(-number);
//            flag = goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//        } else if (flow_status != null && flow_status == 4) {
//            // 删除已通过的出库单，需更新库存表-出库量
//            goodsStorageManageDTO.setOut_number(-number);
//            flag = goodsStorageManageService.updateOrSave(goodsStorageManageDTO);
//        } else {
//            flag = true;
//        }
//        if (!flag) {
//            return 3;
//        }
//        // 构造流程工具类
//        WorkFlowUtil wfu = new WorkFlowUtil<GoodsOutStorage, GoodsOutStorageMapper>(id, userId, GoodsOutStorage.class);
//
//        // 流程id
//        Long wfData_id = wfu.getWfDataId(id);
//
//        return isActual ? wfu.ActualDelete(wfData_id) : wfu.Delete(wfData_id);
//        return 1;
//    }

    @Override
    public Long getStorageNumber(Long id) {
        GoodsStorageManage one = goodsStorageManageService.getOne(Wrappers.<GoodsStorageManage>lambdaQuery().eq(GoodsStorageManage::getGoods_type_id, id));
        if (one == null) {
            throw new CommonException("未知物品");
        } else {
            return one.getStorage_number();
        }
    }
}
